package com.lechuang.exception.handler;

import com.lechuang.exception.CheckException;
import com.lechuang.kit.StringKit;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/**
 * Created by Administrator on 2016/9/26.
 */
public class GlobalExceptionHandler implements HandlerExceptionResolver {
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response,

                                         Object handler, Exception ex) {
        String msg = null;
        response.setContentType("text/html;charset=utf8");
        if(!(ex instanceof CheckException)){
            ex.printStackTrace();
            msg = ex.getClass().toString();
        }
        try {
            PrintWriter writer = response.getWriter();
            if(StringKit.isNotBlank(msg)){
                writer.print(msg);
            }else {
                writer.print(ex.getMessage());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }


        return new ModelAndView();
    }
}
